// pages/tp/tp.js
const app = getApp()
Page({
  data: {
    accessToken: "",
    result: [],
    src: "",
    isCamera: true,
    btnTxt: "拍照"
  },
  onLoad() {
    this.ctx = wx.createCameraContext()
    // 获取accessToken
    var time = wx.getStorageSync("time")
    var curTime = new Date().getTime()
    var timeInt = parseInt(time)
    var timeNum = parseInt((curTime - timeInt) / (1000 * 60 * 60 * 24))
    console.log("=======" + timeNum)
    var accessToken = wx.getStorageSync("access_token")
    console.log("====accessToken===" + accessToken + "a")
    // accessToken超过30天过期
    if (timeNum > 28 || (accessToken == "" ||
        accessToken == null || accessToken == undefined)) {
      this.accessTokenFunc()
    } else {
      this.setData({
        accessToken: wx.getStorageSync("access_token")
      })
    }
  },
  // 第一步，拍照
  takePhoto() {
    var that = this
    if (this.data.isCamera == false) {
      this.setData({
        isCamera: true,
        btnTxt: "拍照"
      })
      return
    }
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          isCamera: false,
          btnTxt: "重拍"
        })
        wx.showLoading({
          title: '正在加载中',
        })
        wx.getFileSystemManager().readFile({
          filePath: res.tempImagePath,
          encoding: "base64",
          success: res => {
            that.getResult(res.data)
          },
          fail: res => {
            wx.hideLoading()
            wx.showToast({
              title: '拍照失败,未获取相机权限或其他原因',
              icon: "none"
            })
          }
        })
      }
    })
  },
  //获取识别结果
  getResult(base64Img) {
    let that = this
    wx.request({
      // url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant?access_token=' + token,
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v1/plant',
      method: 'POST',
      data: {
        access_token: that.data.accessToken,
        image: base64Img
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        console.log(res);
        this.setData({
          result: that.resultFilter(res.data.result)
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  //result结果过滤
  resultFilter(arr) {
    arr.forEach((item) => {
      item.score = (item.score.toFixed(4) * 100).toFixed(2) + '%'
    })
    return arr
  },



  // 获取百度的AccessToken
  accessTokenFunc() {
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token',
      data: {
        grant_type: 'client_credentials',
        client_id: 'xVBluR4U7blzrWh1KFTsE1th', //应用的API Key
        client_secret: 'RGCZ3qDdEpkYhrdI8PGlqjKdG8pPnGV7' //应用的Secret Key
      },
      header: {
        'Content-Type': 'application/json' // 默认值
      },
      success: res => {
        this.setData({
          accessToken: res.data.access_token //获取到token
        })
        console.log('获取到的token', this.data.accessToken)
        wx.setStorageSync("access_token", this.data.accessToken)
        wx.setStorageSync("time", new Date().getTime())
      },
      fail: res => {
        wx.clearStorageSync("access_token")
        wx.showToast({
          icon: 'error',
          title: '调用失败,请重新尝试',
        })
      }
    })
  },
})
